<template>
  <div class="article-create">
    <div class="card">
      <div class="card-title">发表文章</div>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="96px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入文章标题" maxlength="200" show-word-limit />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="form.category" placeholder="请选择分类" style="width: 240px;">
            <el-option v-for="c in categories" :key="c.key" :label="c.label" :value="c.key" />
          </el-select>
        </el-form-item>
        <el-form-item label="封面图" prop="coverImage">
          <el-upload
            v-model:file-list="coverList"
            :auto-upload="false"
            :limit="1"
            accept="image/*"
            list-type="text"
            :on-change="onCoverChange"
            :on-exceed="onCoverExceed"
            :on-remove="onCoverRemove"
          >
            <el-button type="primary">选择图片</el-button>
            <template #tip>
              <div class="el-upload__tip">支持 jpg/png/webp，最大 5MB</div>
            </template>
          </el-upload>
          <div v-if="coverPreviewUrl" class="cover-preview">
            <el-image :src="coverPreviewUrl" style="width: 200px; height: 120px; object-fit: cover; margin-top: 8px;"/>
          </div>
        </el-form-item>
        <el-form-item label="摘要" prop="description" required>
          <el-input type="textarea" v-model="form.description" :rows="3" maxlength="60" show-word-limit placeholder="简短导读" />
        </el-form-item>
        <el-form-item label="正文" prop="content" required>
          <el-input type="textarea" v-model="form.content" :rows="10" placeholder="支持富文本的占位，后续可接入编辑器" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="submitting" @click="onSubmit">发布</el-button>
          <el-button @click="onCancel" :disabled="submitting">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage, type FormInstance, type FormRules, type UploadProps, type UploadUserFile } from 'element-plus'
import { useRouter } from 'vue-router'
import { useArticleStore } from '@/stores/article/article'
import { storeToRefs } from 'pinia'

const categories = [

  { key: '心理咨询', label: '心理咨询' },
  { key: '缓解焦虑', label: '缓解焦虑' },
  { key: '情感危机', label: '情感危机' },
  { key: '改善人际', label: '改善人际' },
  { key: '个人成长', label: '个人成长' },
]

const form = reactive({
  title: '',
  category: '心理咨询',
  coverImage: null as File | null,
  description: '',
  content: '',
})
const formRef = ref<FormInstance>()
const articleStore = useArticleStore()
const { coverPreviewUrl, submitting } = storeToRefs(articleStore)
const coverList = ref<UploadUserFile[]>([])

const rules: FormRules = {
  title: [ { required: true, message: '请输入标题', trigger: 'blur' } ],
  category: [ { required: true, message: '请选择分类', trigger: 'change' } ],
  // 摘要与正文均设为必填，且摘要上限与输入框保持一致（60 字）
  description: [
    { required: true, message: '请输入摘要', trigger: 'blur' },
    { max: 60, message: '摘要不能超过 60 字', trigger: 'blur' },
  ],
  content: [
    { required: true, message: '请输入正文', trigger: 'blur' },
  ],
}

const router = useRouter()

async function onSubmit() {
  try {
    await formRef.value?.validate()
    if (!form.coverImage) {
      ElMessage.error('请先选择封面图')
      return
    }
    // 使用 store 统一发布：先上传封面，再提交元数据
    await articleStore.publishArticle({
      title: form.title,
      category: form.category,
      description: form.description,
      content: form.content,
      status: 'PUBLISHED',
    }, form.coverImage)
    ElMessage.success('发布成功')
    router.push({ name: 'articles' })
  } catch (e: any) {
    if (e) ElMessage.error(e?.message || '发布失败')
  } finally {
    // 状态交由 store 控制，无需手动复位
  }
}

function onCancel() {
  router.back()
}

// 封面上传相关逻辑（仅保存 File，预览使用对象 URL）
const MAX_SIZE = 5 * 1024 * 1024 // 5MB
const onCoverChange: UploadProps['onChange'] = (uploadFile, uploadFiles) => {
  // 仅保留 1 个
  if (uploadFiles.length > 1) {
    uploadFiles.splice(0, uploadFiles.length - 1)
  }
  const raw = uploadFile.raw
  if (!raw) return
  if (!raw.type.startsWith('image/')) {
    ElMessage.error('请上传图片类型文件')
    return
  }
  if (raw.size > MAX_SIZE) {
    ElMessage.error('图片大小不能超过 5MB')
    return
  }
  form.coverImage = raw
  coverList.value = [uploadFile]
  articleStore.setCoverPreview(raw)
}

const onCoverExceed: UploadProps['onExceed'] = (files) => {
  ElMessage.warning('仅允许上传 1 张封面图，已替换为最新选择')
  const f = files?.[0]
  if (!f) return
  // 触发 onChange 流程
  onCoverChange({
    name: f.name,
    percentage: 0,
    status: 'ready',
    size: (f as any).size,
    raw: f as any,
    uid: Date.now().toString(),
  } as any, [
    {
      name: f.name,
      percentage: 0,
      status: 'ready',
      size: (f as any).size,
      raw: f as any,
      uid: Date.now().toString(),
    } as any,
  ])
}

const onCoverRemove: UploadProps['onRemove'] = () => {
  form.coverImage = null
  coverList.value = []
  articleStore.clearCover()
}
</script>
<style scoped>
.article-create { max-width: 880px; margin: 0 auto; padding: 16px; }
.card { background: #fff; border-radius: 12px; padding: 16px; box-shadow: 0 1px 3px rgba(0,0,0,0.06); }
.card-title { font-weight: 600; margin-bottom: 12px; }
.cover-preview { margin-left: 0; }
</style>
